<template>
  <div class="app-container" style="background: #FFFFFF;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户账号ID" prop="customerId" v-if="false">
        <el-input v-model="queryParams.customerId" placeholder="请输入客户账号ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="拨款时间">
        <el-date-picker v-model="dateRange[0]" type="date" value-format="yyyy-MM-dd" placeholder="开始时间"
          style="width: 130px !important;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="">
        <span>至</span>
      </el-form-item>
      <el-form-item label="">
        <el-date-picker v-model="dateRange[1]" type="date" value-format="yyyy-MM-dd" placeholder="结束时间"
          style="width: 130px !important;">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="业务员" prop="ywyName">
        <el-select v-model="queryParams.ywyName" style="width: 160px !important;" filterable placeholder="业务员"
          clearable>
          <el-option v-for="item in ywyOptions" :key="item.userId" :label="item.nickName"
            :value="item.userId.toString()"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="khname">
        <el-input v-model="queryParams.khname" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table border="" v-loading="loading" :data="adjustList" @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }" highlight-current-row class="abc"
      :row-class-name="tableAddClass">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="合同时间" align="center" prop="agrDate" width="100">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.agrDate, "{y}-{m}-{d}") }}</div>
        </template>
      </el-table-column>
      <el-table-column label="合同编号" align="center" prop="agrId" width="140px">
        <template slot-scope="scope">
          <div v-if="scope.row.agrId.includes('X')" title="拨款单处生成" style="color: red;cursor:pointer;">{{ scope.row.agrId
            }}</div>
          <div v-else style="color: rgb(114, 175, 228);cursor:pointer;"
            @click="findkh(2, scope.row, queryParams.pageNum)">{{ scope.row.agrId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="left" prop="khname">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" :title="scope.row.khname">
            {{ scope.row.khname }}</div>
        </template>
      </el-table-column>
      <el-table-column label="关联渠道" align="left" prop="gsname">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" :title="scope.row.gsname">
            {{ scope.row.gsname }}</div>
        </template>
      </el-table-column>
      <el-table-column label="实际渠道" align="left" prop="sjname">
        <template slot-scope="scope">
          <div style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;" :title="scope.row.sjname">
            {{ scope.row.sjname }}</div>
        </template>
      </el-table-column>

      <el-table-column label="实际拨款" align="right" prop="jeBk">
        <template slot-scope="scope">
          <span style="white-space: pre-wrap;">
            {{ toFixed(scope.row.amount-scope.row.hsamount) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="打款金额" align="right" prop="jeDk">
        <template slot-scope="scope">
          <span style="white-space: pre-wrap;">
            {{ toFixed(scope.row.jeDk) }}
          </span>
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column label="银行打款" align="right" prop="jeFk">
        <template slot-scope="scope">
          <span style="white-space: pre-wrap;">
            {{ toFixed(scope.row.bSkje) }}
          </span>
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column label="打款差额" align="right" prop="jeFq">
        <template slot-scope="scope">
          <span style="white-space: pre-wrap;color:#09be21" v-if="toFixed(scope.row.bSkje-scope.row.jeDk)<0">
            {{ toFixed(scope.row.bSkje-scope.row.jeDk) }}
          </span>
          <span style="white-space: pre-wrap;color:#f10707" v-else>
            +{{ toFixed(scope.row.bSkje-scope.row.jeDk) }}
          </span>
        </template>
      </el-table-column>
      </el-table-column>

      >
      <el-table-column label="业务员" align="center" prop="ywyName" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="[15,20,30,50]"
      @pagination="getList" />


    <el-row style="margin-top: 25px;">
      <el-col :span="24">
        <el-card class="update-log">
          <div class="body">
            <el-row>
              <el-col :span="8" align="right">

                <p style="font-size: 18px; font-weight: bold;">

                </p>
              </el-col>

              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">实际拨款</h5>
                <p style="font-size: 18px; font-weight: bold;color:brown;">
                  {{ toFixed(formsum.amount-formsum.hsamount) }}
                </p>
              </el-col>
              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">打款金额</h5>
                <p style="font-size: 18px; font-weight: bold;color:cadetblue;">
                  {{ toFixed(formsum.jeDk) }}
                </p>
              </el-col>

              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">银行打款</h5>
                <p style="font-size: 18px; font-weight: bold;color:rgb(17, 14, 224);">
                  {{ toFixed(formsum.bSkje) }}
                </p>
              </el-col>
              <el-col :span="4" align="right">
                <h5 style="color: black; font-weight: bold;margin-top: 10px;margin-bottom: 0px;">打款差额</h5>
                <p style="font-size: 18px; font-weight: bold;color:rgb(255, 0, 128);">
                  {{ toFixed(formsum.bSkje-formsum.jeDk) }}
                </p>
              </el-col>


            </el-row>

          </div>
        </el-card>
      </el-col>
    </el-row>


  </div>
</template>

<script>
  // import { listAdjust, listAdjustsum, listAdjustsumdk, listAdjustsumddje, getAdjust, delAdjust, addAdjust, updateAdjust } from "@/api/AdjustMain/adjust";
  import { listbyBB, listbySum } from "@/api/AgreementMain/agreement";
  // import { getCustomerbalances } from "@/api/CustomerbalancesMain/customerbalances";
  import { getUserProfile, listuser, listJsy } from "@/api/system/user";
  // import { listCustomerinfo } from "@/api/CustomerinfoMain/customerinfo";
  // import { listAppropriation, getAppropriation, delAppropriation, addAppropriation, updateAppropriation } from "@/api/AppropriationMain/appropriation";
  // import { listDealerAll, addDealersj, } from "@/api/DealerMain/dealer";
  import { GetMonA, GetMonB } from "@/api/public";
  export default {
    dicts: ["tz_type", "tzlx"],
    name: "Agreementbyreport",
    data() {
      return {
        formsum:{},
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        dateRange: [],
        // 调帐记录表格数据
        adjustList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 15,
          customerId: null,
          customerName: null,
          operationType: null,
          amount: null,
          currency: null,
          applyScene: null,
          operationTime: null,
          measureId: null,
          other1: null,
          other2: null,
          other3: null,
          other4: null,
          other5: null,
          ywyName: null,
          khname: null,
          deaname: null,
          applxs: [], //到期状态多个值用于查询，这个实体临时用下
        },
        // 表单参数
        form: {},
        // 表单参数
        form1: {

        },
        jeform: {
          bkje: null,
          ddje: null,
          dkje: null,
        },
        // 表单校验
        rules: {
        },
        // 表单校验
        rules1: {
        },      //客户余额
        khye: "0.00",
        BkOptions: [], //拨款人
        ywyOptions: [],//业务员
        //分配客户相关
        openkh: false,
        titlekh: "",
        khList: [],
        totalkh: 0,
        khid: [],
        khmc: [],
        // 查询参数
        queryParamsKh: {
          pageNum: 1,
          pageSize: 10,
          customer: null,
          verifiedStatus: 2,
          dead: null,
        },

        //分配渠道相关
        openqd: false,
        titleqd: "",
        dealerList: [],
        deid: [],//分配选中的渠道
        dename: [],
        qdval: {//分配时，传值的parm
          realDea: null,
          orderId: null,
        },
        totalqd: 0,
        // 查询参数
        queryParamsQd: {
          pageNum: 1,
          pageSize: 10,
          Dtype: 2,
          deaName: null,
        },


        //分配合同相关
        openht: false,
        titleht: "",
        htList: [],
        htid: [],//分配选中的渠道
        jebk: [], //订单金额
        totalht: 0,
        // 查询参数
        queryParamsHt: {
          pageNum: 1,
          pageSize: 10,
          Dtype: 2,
          deaName: null,
        },

      };
    },
    created() {
      this.dateRange[0] = GetMonA(3);
      this.dateRange[1] = GetMonB();
      this.getList();
      this.getselList();
      this.getsum();
    },
    methods: {
      //查看合同
      findkh: function (atype, row) {
        var rid = "";
        if (row != null)
          rid = row.flag;

        let routeData = this.$router.resolve({ path: '/htxg/agreementht', query: { atype: atype, did: null, aid: rid, } });
        window.open(routeData.href, '_blank');
        // this.$router.push(
        //   {
        //     path: '/htxg/agreementht',
        //     methods: 'post',
        //     query: {
        //       atype: atype, //表示添加
        //       did: null,
        //       aid: rid,
        //     }
        //   })
      },
      //修改table行颜色
      tableAddClass({ row, rowIndex }) {
        if (row.applx == 2)
          return "tr-red";
        else if (row.applx == 1)
          return "tr-blue";
        else
          return "";

      },
      /** 查询调帐记录列表 */
      getList() {
        this.loading = true;
        listbyBB(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          console.log(response);
          this.adjustList = response.rows;
          this.total = response.total;
          this.loading = false;
        });

      },
      getListsum() {

        this.jeform.bkje = "0.00";
        //this.jeform.ddje = "0.00";
        listAdjustsum(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          console.log(response.rows[0]);
          this.jeform.bkje = response.rows[0].amount;
          //this.jeform.ddje = response.rows[0].ddje;
          this.jeform.dkje = response.rows[0].dkje;
        });
      },

      getsum() {
        this.jeform.bkje = "0.00";

        listbySum(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.formsum = response.data[0];
          console.log(this.formsum);
        
        });
      },
      getListsumdk() {
        // this.jeform.dkje = "0.00";
        // listAdjustsumdk(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        //   this.jeform.dkje = response.rows[0].dkje;
        // });
      },
      getListsumddje() {
        this.jeform.ddje = "0.00";
        listAdjustsumddje(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.jeform.ddje = response.rows[0].ddje;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 查询客户列表 下拉绑定*/
      getselList() {
        //绑定业务员
        listuser(this.queryParamsUser).then(response => {
          this.BkOptions = response.rows;
          this.ywyOptions = response.rows;
        });
      },

      // 表单重置
      reset() {
        this.form = {
          transId: null,
          customerId: null,
          customerName: null,
          operationType: null,
          amount: null,
          currency: null,
          applyScene: null,
          operationTime: null,
          measureId: null,
          other1: null,
          other2: null,
          other3: null,
          other4: null,
          other5: null
        };
        this.resetForm("form");
      },
      // 表单重置
      reset1() {
        this.form1 = {
          aid: null,
          appTime: null,
          deaId: null,
          customer: null,
          customerIdHw: null,
          agreeid: null,
          appJe: null,
          custJe: null,
          appType: null,
          appLx: null,
          mark: null,
          appUser: null,
          ywyName: null,
          appStatus: null,
          appCreatetime: null,
          other1: null,
          other2: null,
          other3: null,
          other4: null,
          other5: null,
          gsname: null,
          khname: null,
          realname: null,
          realdea: null,
        };
        this.resetForm("form1");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;

        this.getList();
        this.getsum();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.applxs = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.transId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加调帐记录";
      },
      handleClickTableRowD(row, event, column) {
        this.$refs.fileTableD.toggleRowSelection(row);
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.reset1();
        const transId = row.transId || this.ids
        getAdjust(transId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改调帐记录";
        });
        getAppropriation(transId).then(response => {
          if (response.data != undefined) {
            console.log(this.form1);
            this.form1 = response.data;
            this.open = true;
            this.getkhye();
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        // this.$refs["form"].validate(valid => {
        //   if (valid) {
        //     if (this.form.transId != null) {
        //       updateAdjust(this.form).then(response => {
        //         this.open = false;
        //         this.getList();
        //       });
        //     } else {
        //       addAdjust(this.form).then(response => {
        //         this.open = false;
        //         this.getList();
        //       });
        //     }
        //   }
        // });
        this.$refs["form1"].validate(valid => {
          if (valid) {
            this.form1.aid = this.form.transId;
            addAppropriation(this.form1).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });

          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const transIds = row.transId || this.ids;
        this.$modal.confirm('是否确认删除调帐记录编号为"' + transIds + '"的数据项？').then(function () {
          return delAdjust(transIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('AdjustMain/adjust/export', {
          ...this.queryParams
        }, `adjust_${new Date().getTime()}.xlsx`)
      },




      /****渠道操作相关 */
      showsjqd(type) {
        this.gsbtshow = true;
        this.titleqd = "选择渠道";
        this.openqd = true;
        this.getListDea();
      },
      /** 查询分配渠道列表 */
      getListDea() {
        this.loading = true;
        listDealerAll(this.queryParamsQd).then((response) => {
          this.dealerList = response.rows;
          this.totalqd = response.total;
          this.loading = false;

        });
      },
      // 分配弹窗多选框选中数据1 渠道
      handleSelectionChangeQd(selection) {
        this.deid = selection.map(item => item.deaId)
        this.dename = selection.map(item => item.deaName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      cancelqd() {
        this.openqd = false;
      },
      //渠道点行选中
      handleClickTableRowB(row, event, column) {
        this.$refs.fileTableB.toggleRowSelection(row);
      },
      /**分配渠道窗口重置 */
      resetQueryQd() {
        this.resetForm("queryFormQd");
        this.handleQdQuery();
      },
      /** 搜索按钮操作 */
      handleQdQuery() {
        this.getListDea();

      },
      //确定选择渠道
      gsqdClick() {
        if (this.deid.length > 1) {
          this.$modal.msgWarning("只能选择一个渠道");
          return;
        }
        // this.form1.deaId = this.deid[0];
        // this.form1.gsname = this.dename[0];
        this.form1.realdea = this.deid[0];
        this.form1.realname = this.dename[0];
        this.cancelqd();
      },

      /** 选择客户相关事件 */
      showkh() {
        this.openkh = true;
        this.titlekh = "选择客户";
        this.getListKh();
      },
      khcancel() {
        this.openkh = false;
      },
      /** 搜索按钮操作 */
      handleKhQuery() {
        this.getListKh();
      },
      /**分配客房窗口重置 */
      resetQueryKh() {
        this.resetForm("queryFormKh");
        this.handleKhQuery();
      },
      /** 分配客户多选框选中数据1 客户*/
      handleSelectionChangeKh(selection) {
        this.khid = selection.map(item => item.customerIdHw)
        this.khmc = selection.map(item => item.customer)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleClickTableRowA(row, event, column) {
        this.$refs.fileTableA.toggleRowSelection(row);
      },
      /** 查询分配客户列表 */
      getListKh() {
        this.queryParamsKh.deaId = this.form.deaid;
        listCustomerinfo(this.queryParamsKh).then(response => {
          this.totalkh = response.total;
          this.khList = response.rows;
        });
      },
      /** 分配客户操作 */
      khClick() {
        if (this.khid.length > 1) {

          this.$modal.msgWarning("只能选择一个客户");
          return;
        }
        this.form1.customerIdHw = this.khid[0];
        this.form1.khname = this.khmc[0];
        this.khcancel();
        this.getkhye();
      },
      //查询客户余额数据
      getkhye() {
        getCustomerbalances(this.form.customerIdHw).then(response => {
          console.log(response.data);
          this.khye = this.toFixed(response.data.amount);

        });
      },

      /** 选择合同相关事件 */
      showht() {
        this.openht = true;
        this.titleht = "选择合同";
        this.getListHt();
      },
      /** 查询合同列表 */
      getListHt() {
        this.loading = true;
        listAgreement(this.queryParamsHt).then(response => {
          this.htList = response.rows;
          this.totalht = response.total;
          this.loading = false;
        });
      },
      htcancel() {
        this.openht = false;
      },
      /** 搜索按钮操作 */
      handleHtQuery() {
        this.getListHt();
      },
      /**分配合同窗口重置 */
      resetQueryHt() {
        this.resetForm("queryFormHt");
        this.handleHtQuery();
      },
      /** 分配合同多选框选中数据1 */
      handleSelectionChangeHt(selection) {
        this.htid = selection.map(item => item.agrId)
        this.jebk = selection.map(item => item.ddje)
        this.khid = selection.map(item => item.customerId)
        this.khmc = selection.map(item => item.khname)

        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleClickTableRowC(row, event, column) {
        this.$refs.fileTableC.toggleRowSelection(row);
      },

      /** 分配合同确认操作 */
      htClick() {
        if (this.htid.length > 1) {
          this.$modal.msgWarning("只能选择一个合同");
          return;
        }
        this.form1.agreeid = this.htid[0];
        this.form1.custJe = this.toFixed(this.jebk[0]);
        this.form1.customerIdHw = this.khid[0];
        this.form1.khname = this.khmc[0];

        this.htcancel();

      },

      //保留两位，不足补位
      toFixed(num) {
        return (Math.round(num * 100) / 100).toFixed(2);
      },
    }
  };
</script>
<style scoped>
  .app-container /deep/ .el-table .tr-red {
    color: red !important;
  }

  .app-container /deep/ .el-table .tr-blue {
    color: blue !important;
  }
</style>